import 'package:dio/dio.dart';
import '../../../shared/services/auth_service.dart';

class AuthInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    // 获取存储的token
    final token = AuthService.instance.getToken();
    
    // 如果token存在，添加到请求头
    if (token != null && token.isNotEmpty) {
      options.headers['Authorization'] = 'Bearer $token';
    }
    
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    // 处理响应中的token更新
    final newToken = response.headers.value('x-new-token');
    if (newToken != null && newToken.isNotEmpty) {
      AuthService.instance.saveToken(newToken);
    }
    
    super.onResponse(response, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    // 处理401未授权错误
    if (err.response?.statusCode == 401) {
      // 清除过期的token
      AuthService.instance.clearToken();
      
      // 可以在这里触发重新登录
      // Get.offAllNamed('/login');
    }
    
    super.onError(err, handler);
  }
}